﻿#include "KIndicatorLayer.h"
#include <QPainter>
#include <QPen>
#include <QRandomGenerator>

#include "KLineCanvas.h"
#include "KLineCanvasContext.h"
#include "KLineViewContext.h"
#include "KColorStyle.h"
#include "KBarWidthStyle.h"

class KIndicatorLayer::KIndicatorLayerPrivate :public QObject
{
public:
	QVector<QVariant> data;
public:
	KIndicatorLayerPrivate(QObject*parent) :QObject(parent)
	{	}
};

KIndicatorLayer::KIndicatorLayer(QObject *parent)
	: KLineLayer(parent),private_ptr(new KIndicatorLayerPrivate(this))
{
	setType(KLayer::LAYER_TYPE_INDICATOR);
}

KIndicatorLayer::~KIndicatorLayer()
{
}


void KIndicatorLayer::draw(QPainter*p)
{
	if (!visible())
		return;

	if (!private_ptr->data.count())
		return;

	KLineViewContext*view_context = viewContext();
	KLineCanvasContext*canvas_ctx = view_context->canvas_context;
	if (0 == canvas_ctx->canvas_colcount)
		return;


	int n = private_ptr->data.count() - canvas_ctx->item_startidx;
	if (n <= 0)
		return;

	int endidx = private_ptr->data.count() - 1;
	if (canvas_ctx->item_startidx + canvas_ctx->canvas_colcount - 1 <= endidx)
		endidx = canvas_ctx->item_startidx + canvas_ctx->canvas_colcount - 1;

	QPoint pt;
	QPolygon polygon;

	QRectF rc = canvas_ctx->rect_firstcol;// .intersected(private_ptr->view_context->rt_view);
	int baritem_center = KBarWidthStyle::item(canvas_ctx->barwidthstyle_idx)->center();
	for (int i = canvas_ctx->item_startidx; i <= endidx; i++) {
		if (i != canvas_ctx->item_startidx)
			rc.translate(canvas_ctx->canvas_colwidth, 0);
		pt.setX(rc.left() + baritem_center);
		pt.setY(view_context->posYAtValue(private_ptr->data[i].toDouble()));
		polygon.append(pt);
	}

	QPainterPath	pp;
	pp.addPolygon(polygon);

	p->save();

	p->setPen(color());
	p->drawPath(pp);

	p->restore();
}

bool KIndicatorLayer::contain(const QPointF&pt)
{
	return false;
}
int KIndicatorLayer::dataLength()
{
	return private_ptr->data.count();
}
void KIndicatorLayer::setData(int type, QVector<QVariant>*_)
{
	if (_)
		private_ptr->data = *_;
	else
		private_ptr->data.clear();
}
QVector<QVariant>* KIndicatorLayer::data(int type)
{
	return &private_ptr->data;
}
bool KIndicatorLayer::getMaxMinValue(int start_idx, int count, double*max_v, double*min_v)
{
	if (!private_ptr->data.count())
		return false;
	int n = private_ptr->data.count() - start_idx;
	if (start_idx < 0 || !n || !count) {
		return false;
	}
	if (n < count)
		count = n;

	bool ok = false;
	double axv, inv, t;

	int end_idx = start_idx + count - 1;

	for (int i = start_idx; i <= end_idx; i++) {
		if (private_ptr->data[i].type() != QVariant::Double) {
			if (!private_ptr->data[i].canConvert<double>())
				continue;
		}
		t = private_ptr->data[i].toDouble();
		if (!ok) {
			ok = true;
			axv = inv = t;
		}
		else {
			if (t > axv)
				axv = t;
			if (t < inv)
				inv = t;
		}
	}

	if (ok) {
		*max_v = (axv);
		*min_v = (inv);
	}
	return ok;
}

